import org.apache.commons.io.IOUtils
import org.apache.commons.fileupload.util.Streams
import org.apache.commons.fileupload.servlet.ServletFileUpload
import com.google.appengine.api.datastore.Entity
import com.queixate.model.*

uploads = [:]  // Store result from multipart content.
if (ServletFileUpload.isMultipartContent(request)) {
    def uploader = new ServletFileUpload()  // Cannot use diskbased fileupload in Google App Engine!
    def items = uploader.getItemIterator(request)
    while (items.hasNext()) {
        def item = items.next()
        def stream = item.openStream() 
        try {
            if (item.formField) {  // 'Normal' form field.
                params[item.fieldName] = Streams.asString(stream)
            } else {
                // Assign upload file contents to uploads map. 
                // The value is also a map with the keys name, contentType and data.
                uploads = [
                    name: item.name,
                    contentType: item.contentType,
                    data: IOUtils.toByteArray(stream)
                ]
            }
        } finally {
            IOUtils.closeQuietly stream
        }
    }
}

if (params.provincia) {
    handle(params.provincia)
} else {
	sout << "faltan parametros"
}


def guardaObjeto(def o) {

	Concello concello = new Concello([nome:o.nome])
	concello.setProvincia(o.provincia as Long)
	concello.nomeMinusculas = concello.nome.toLowerCase()
	
	concello.store()

}

def handle(def provincia) {

	//Obtiene las lineas del fichero recibido
	
	def lineas = []
	def objetos = []
	
	if (uploads?.data) {
	
		def bis = new ByteArrayInputStream(uploads.data)
		lineas = IOUtils.readLines(bis,"UTF-8")
	}
	
	
	if (lineas) {
	
		lineas.each {
			def valores = it.split(",")
			
			if (valores && valores.size() == 1) {
				def o = [nome:valores[0], provincia:provincia]
				
				objetos << o
			}
			
		}
	
	}
	
	objetos.each {
		 guardaObjeto(it)
	}
	
	

    // Build response HTML.
    html.html {
        head {
            title 'Result of Upload'
        }
        body {
            h1 'Result of Upload'
            h2 'Parameters'
            ul {
                params.each {
                    li "Received parameter '$it.key' with value '$it.value'"
                }
            }
            h2 'Uploads'
            ul {
            	objetos .each {
	            	li "$it"            	
            	}
            
            }
        }
    }
    
    
    
}

